package hr.tvz.lab.tom.malwaredb.info;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.facebook.drawee.view.SimpleDraweeView;

import java.util.List;

import hr.tvz.lab.tom.malwaredb.R;

/**
 * RecyclerView Adapter for MalwareObject media list in InfoActivity.
 */
public class RecyclerViewGalleryAdapter extends RecyclerView.Adapter<RecyclerViewGalleryAdapter.ViewHolder> {

    List<String> mediaList;

    public RecyclerViewGalleryAdapter(List<String> mediaList) {
        this.mediaList = mediaList;
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        SimpleDraweeView mediaView;
        ImageView videoIcon;
        String mediaLink;

        public ViewHolder(View itemView) {
            super(itemView);
            mediaView = (SimpleDraweeView) itemView.findViewById(R.id.mediaView);
            videoIcon = (ImageView) itemView.findViewById(R.id.videoIcon);
            mediaView.setOnClickListener(this);
            videoIcon.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            // Opens page from link source.
            Intent webActivity = new Intent(Intent.ACTION_VIEW);
            webActivity.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            webActivity.setData(Uri.parse(mediaLink));
            v.getContext().startActivity(webActivity);
        }
    }

    @Override
    public RecyclerViewGalleryAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_list_gallery, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerViewGalleryAdapter.ViewHolder holder, int position) {
        holder.mediaLink = mediaList.get(position);
        // If media content is YouTube video, add YT thumbnail and play icon.
        if (mediaList.get(position).indexOf("youtube.com/watch?v=") != -1) {
            String ytValue = mediaList.get(position).substring(mediaList.get(position).indexOf("watch?v=") + 8);
            holder.mediaView.setImageURI(Uri.parse("https://i.ytimg.com/vi/" + ytValue + "/hqdefault.jpg?custom=true&w=480&h=360"));
            holder.mediaView.setId(position);
            holder.videoIcon.setVisibility(View.VISIBLE);
            holder.videoIcon.setId(position);
        } else {
            holder.mediaView.setImageURI(Uri.parse(mediaList.get(position)));
            holder.mediaView.setId(position);
            holder.videoIcon.setVisibility(View.GONE);
            holder.videoIcon.setId(position);
        }
    }

    @Override
    public int getItemCount() {
        return mediaList.size();
    }
}
